package com.jy.adscm.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jy.adscm.annotation.AdscmLogger;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.security.service.SecurityLoginUserService;
import com.jy.adscm.security.support.SimpleResponse;
import com.jy.adscm.system.service.JyMenuService;
import com.jy.adscm.system.service.JyUserService;
import com.jy.adscm.system.utils.AdscmSystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yyy
 * @ClassName AdscmSystemController
 * @Description 用户管理Controller
 * @date 2018/8/1 17:34
 */
@RestController
@RequestMapping("/adscm/system/user")
@CrossOrigin
public class AdscmUserController {

    @Autowired
    JyUserService jyUserService;
    @Autowired
    JyMenuService jyMenuService;

    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    SecurityLoginUserService securityLoginUserService;

//    @Value("${spring.http.multipart.location}")
//    String location;

    /**
     * 分页查询所有用户信息
     * @return
     */
    @AdscmLogger("分页查询所有用户信息")
    @RequestMapping("/allUserPage/{currentPage}/{pageSize}")
    public SimpleResponse getAllUserPage(@PathVariable int currentPage,@PathVariable int pageSize)throws AdscmSystemException{

        Page<JyUser> page = new Page<JyUser>(currentPage,pageSize);

        page = jyUserService.getUserPage(page);

        return new SimpleResponse("200","分页查询用户信息成功",page);

    }
    @RequestMapping("/selectAllUser")
    public SimpleResponse select()throws AdscmSystemException{
        Wrapper<JyUser> jyUserWrapper=new EntityWrapper<>();
        jyUserWrapper.setSqlSelect("id","name");
        jyUserWrapper.eq("enabled",1);
        List<JyUser> jyUsers = jyUserService.selectList(jyUserWrapper);
        return new SimpleResponse("200","查询用户信息成功",jyUsers);

    }
    /**
     * 保存用户信息
     * @return
     */
    @AdscmLogger("保存用户信息")
    @RequestMapping("/saveOrUpdateUsersMsg")
    public SimpleResponse saveOrUpdateUsersMsg(HttpServletRequest request,JyUser user)throws AdscmSystemException{


        List<String> paths = null;

        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());

//        if(multipartResolver.isMultipart(request)){
//            //将request变成多部分request
//            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//
//            paths = AdscmSystemUtils.getInstance().uploadFile(multiRequest,location);
//        }


        if (paths != null && paths.size()>0){
            user.setPhoto(paths.get(0));
        }
        jyUserService.insertOrUpdate(user);

        return new SimpleResponse("200","保存用户信息成功",null);

    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @AdscmLogger("删除用户")
    @RequestMapping("/delUser/{userId}")
    public SimpleResponse delUser(@PathVariable int userId) throws AdscmSystemException{

        jyUserService.delUser(userId);

        return new SimpleResponse("200","删除用户成功",null);
    }
    /**
     * 给用户授予角色
     * @param roleIds
     * @param userId
     * @return
     */
    @AdscmLogger("给用户授予角色")
    @RequestMapping("/usersRoles/{userId}")
    public SimpleResponse setUsersRoles(String roleIds,@PathVariable int userId) throws AdscmSystemException{

        List<Integer> ids = new ArrayList<>();
        if(roleIds != null &&!"".equals(roleIds)){
            String[] ids_str = roleIds.split(",");
            for (String s : ids_str) {
                ids.add(Integer.parseInt(s));
            }
        }
        jyUserService.setUserRoles(ids,userId);

        return new SimpleResponse("200","给用户授予角色成功",null);
    }

    /**
     * 修改密码
     * @param userId
     * @param password
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/editUsersPwd/{userId}/{password}")
    public SimpleResponse editUsersPwd(@PathVariable Integer userId,@PathVariable String password,HttpServletRequest request) throws AdscmSystemException{

        JyUser user = jyUserService.selectById(userId);

        if (user != null){
            String encodePwd = passwordEncoder.encode(password);
            user.setPassword(encodePwd);
            user.setRemark(password);
            jyUserService.updateById(user);

            securityLoginUserService.logout(request);//登出系统
            return new SimpleResponse("200","修改密码成功，请重新登录",null);
        }
        throw new AdscmSystemException("没有查询到用户，修改密码失败...");
    }

}
